package com.vtech.spring.commons;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2018/8/8 18:35
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Object handler(Exception e, HttpServletRequest req) throws JsonProcessingException {
        //业务异常
        if (e instanceof BusinessException && isAjax(req)) {
            return new ResponseEntity<Object>(e.getMessage(), new HttpHeaders(), ((BusinessException) e).getHttpStatus());
        } else {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg", e.getMessage());
            mv.addObject("url", req.getRequestURL());
            mv.addObject("stackTrace", e.getStackTrace());
            mv.setViewName("error");
            return mv;
        }
    }

    public static boolean isAjax(HttpServletRequest request)
    {
        boolean flag = false;
        String type = request.getHeader("X-Requested-With");
        if (type != null && type.equalsIgnoreCase("XMLHttpRequest")) {
            flag = true;
        }
        return flag;
    }


}
